//
//  AppDelegate.m
//  WanLian
//
//  Created by muzhuang on 2018/8/22.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "AppDelegate.h"
#import "WLTabBarController.h"
#import "WLGuideViewController.h"
#import "IQKeyboardManager.h"
#import "AFNetworkActivityIndicatorManager.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
//#import <AdSupport/AdSupport.h>

#import <UMCommon/UMCommon.h>
//#import <UMShare/UMShare.h>
#import "WLUpLoadCenter.h"
#import "WLDownLoadCenter.h"


@interface AppDelegate ()<UNUserNotificationCenterDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [application setApplicationIconBadgeNumber:0];
    if ([[WLUseManager shareUser] isLogin]) {
        [[WLUseManager shareUser] requestRouterInfo];//请求用户绑定的路由器信息
    }
    //网络监测
    [self netWorkMonitor];
    self.window.backgroundColor =[UIColor whiteColor];
    [self setBarNavAppearance];
    _wlTabbarController = [[WLTabBarController alloc] init];
    
    //获取当前版本
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    //获取旧版本
    NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"showGuideView"];
    if ([currentVersion isEqualToString:oldVersion] == NO)
    {
        WLWkSelf
        WLGuideViewController *guideView = [[WLGuideViewController alloc]init];
        self.window.rootViewController = guideView;
        guideView.didSelectedEnter = ^{
            [weakSelf guideViewBacked];
        };
    }
    else
    {
        self.window.rootViewController = _wlTabbarController;
    }
    
    [self.window makeKeyAndVisible];
    
    //极光推送
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        // 可以添加自定义categories
//        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
//        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
//        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
//            [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
//            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //            [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    //                if (granted) {
    //                    //                MZLog(@"Notification center Open success");
    //                } else {
    //                    NSLog(@"Notification center Open failed");
    //                }
    //            }];
    //            [[UIApplication sharedApplication] registerForRemoteNotifications];
//        }
//        else
//        {
//            UIUserNotificationSettings *notiSet = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound|UIUserNotificationTypeAlert|UIUserNotificationTypeBadge) categories:nil];
//            [application registerUserNotificationSettings:notiSet];
//            [application registerForRemoteNotifications];
//        }
//    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:@"278e4019940b2abdefe72631"
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            WLLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            WLLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    //初始化友盟
    [UMConfigure initWithAppkey:@"5c074919b465f5abd10001ef" channel:@"App Store"];
//    [self configUSharePlatforms];
    [UMConfigure setLogEnabled:YES];
    IQKeyboardManager *keyManage = [IQKeyboardManager sharedManager];
    keyManage.enable = YES;
    keyManage.shouldResignOnTouchOutside = YES;
    [keyManage setEnableAutoToolbar:NO];
    [keyManage setKeyboardDistanceFromTextField:50.0];
    
//    [[WLSocketManager sharedSocketManager] connectServerHost];
    
    return YES;
}
-(void)setBarNavAppearance
{
    UINavigationBar *navigationBar = [UINavigationBar appearance];
    [navigationBar setBarTintColor:[UIColor whiteColor]];
//    [navigationBar setBackgroundImage:[WLCommonTool createImageWithColor:[UIColor whiteColor]] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage new]];
    [navigationBar setTintColor:wlLightTextColor];
    [navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:wlBlackColor,NSFontAttributeName:[WLCommonTool fontTypePingFangSCMedium:17]}];
    
//    if (@available(iOS 11.0, *)){
//        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
//    }
    if (@available(iOS 12.0, *)) {
        [[UITabBar appearance] setTranslucent:NO];
    }
}

- (void)guideViewBacked
{
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"showGuideView"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.window.rootViewController = self.wlTabbarController;
    //转场动画
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5;
    transition.type = @"rippleffect";
    [self.window.layer addAnimation:transition forKey:nil];
    [WLCommonTool versionUpdateCheck];
}

- (void)netWorkMonitor
{
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];//
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable)
        {
            [[WLSocketManager sharedSocketManager] userManualdisconnect];
            if ([WLCommonTool judgeNeedShowSettingAlert]) {
                [SVProgressHUD showAndAutoCloseWithStatus:@"连接已断开" delayTime:1.f];
            }
        }
        else
        {
            if ([[WLUseManager shareUser] isLogin] && ![[WLUseManager shareUser] routerModel] ) {
                [[WLUseManager shareUser] requestRouterInfo];
            } else if ([[WLUseManager shareUser] isLogin] && [[WLUseManager shareUser] routerModel])
            {
                WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
                
                if ([socketManager.routerSocket.connectedHost isEqualToString:HOST_ROUTER]==NO)
                {
                    BOOL connectedWifi = [WLCommonTool isConnectedTianYiLian];
                    if (connectedWifi) {
                        if (socketManager.routerSocket.isConnected)
                        {
                            [socketManager disconnect];
                            //                        [self linkRouterTest:0.5];
                        }
                        else
                        {
                            [socketManager connectServerHost];
                            //                        [socketManager routerSocketRegister];
                        }
                    }
                }
                else
                {
                    if (socketManager.isRegistered==NO)
                    {
                        [socketManager routerSocketRegister];
                    }
                }
            } 
//            if ([WLCommonTool judgeNeedShowSettingAlert]) {
//                if (![WLCommonTool isConnectedTianYiLian]) {
//                    [SVProgressHUD showAndAutoCloseWithStatus:@"连接已断开" delayTime:1.f];
//                    [WLCommonTool showAlrtToSettingWithTitle:@"请连接到您的天翼链路由器WiFi。" message:nil cancel:@"取消" confirmStr:@"连接"];
//                }
//            }
        }
    }];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    // 实现如下代码，才能使程序处于后台时被杀死，调用applicationWillTerminate:方法
//    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){}];
    [self startBgTask];
}

- (void)startBgTask{
    UIApplication *application = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [[WLDownLoadCenter shareInstance] pauseCurrentTask];
        [[WLUpLoadCenter shareInstance] pauseCurrentTask];
        //这里延迟的系统时间结束
//        NSLog(@"%f",application.backgroundTimeRemaining);
    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (![[WLUseManager shareUser] isLogin] || ![[WLUseManager shareUser]routerModel])
    {
        return;
    }
    WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi)
    {
        BOOL connectedWifi = [WLCommonTool isConnectedTianYiLian];
        if (connectedWifi) {
            if (socketManager.routerSocket.isConnected&&[socketManager.routerSocket.connectedHost isEqualToString:HOST_REMOTE])
            {
                [socketManager disconnect];
    //            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5/*延迟执行时间*/ * NSEC_PER_SEC));
    //
    //            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    //                [socketManager connectServerHost];
    //            });
            }
        }
        else if (socketManager.routerSocket.isDisconnected)
        {
            [socketManager connectRemoteServerHost];
        }
    }
    else if (socketManager.routerSocket.isDisconnected)
    {
        [socketManager connectRemoteServerHost];
    }
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)linkRouterTest:(double)delay
{
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay/*延迟执行时间*/ * NSEC_PER_SEC));
//    WLLog(@"delay out:%f",delay)
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi)
        {
//            WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
//            if ([socketManager.routerSocket.connectedHost isEqualToString:HOST_ROUTER]==NO)
//            {
//                [socketManager connectServerHost];
//            }
//            WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
            if ([socketManager.routerSocket.connectedHost isEqualToString:HOST_ROUTER]==NO)
            {
                BOOL connectedWifi = [WLCommonTool isConnectedTianYiLian];
                if (connectedWifi) {
                    if (socketManager.routerSocket.isConnected)
                    {
                        [socketManager disconnect];
                    }
                    else
                    {
                        [socketManager connectServerHost];
    //                    [socketManager routerSocketRegister];
                    }
                }
                else
                {
                    if (socketManager.routerSocket.isDisconnected)
                    {
                        [socketManager connectRemoteServerHost];
                    }
                }
            }
            else
            {
                if (socketManager.isRegistered==NO)
                {
                    [socketManager routerSocketRegister];
                }
            }
        }
        else if (socketManager.routerSocket.isDisconnected)
        {
            [socketManager connectRemoteServerHost];
        }
    });
//    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi)
//    {
//        WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
//        if (socketManager.routerSocket.isDisconnected)
//        {
//            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay/*延迟执行时间*/ * NSEC_PER_SEC));
//
//            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                [socketManager connectServerHost];
//            });
//        }
//        else
//        {
//            [socketManager disconnect];
//        }
//    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken
{
    NSString *dtoken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    dtoken = [dtoken stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [JPUSHService registerDeviceToken:deviceToken];
    NSString *userTag = [[[WLUseManager shareUser] getUserInformation] userTag];
    if (userTag.length > 0) {
        [JPUSHService setAlias:userTag completion:nil seq:0];
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(nonnull NSError *)error
{
    
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    WLLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshLoacalMessageNofication object:nil];
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
//        [rootViewController addNotificationCount];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    //NSDictionary *userInfo = notification.request.content.userInfo;
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
{
    NSDictionary *userInfo = response.notification.request.content.userInfo;
//    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        //远程推送接受
//        [self addPushGather:userInfo];
//    }else{
//        //本地推送接受
//        [self addPushGather:userInfo];
//    }
//    [self launchFromPushMsg:userInfo];
    completionHandler();
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshLoacalMessageNofication object:nil];
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        WLLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
//        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        WLLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        WLLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
//        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        WLLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxdc1e388c3822c80b" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:@"http://mobile.umeng.com/social"];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:@"wxdc1e388c3822c80b" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105821097"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
//
//    /* 设置新浪的appKey和appSecret */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
    
}
/*
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    NSLog(@"applicationDidReceiveMemoryWarning");
}
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
{
    if (completionHandler) {
        completionHandler();
    }
//    self.backgroundSessionCompletionHandler = completionHandler;
}

*/
@end
